package cn.tedu.store.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.tedu.store.controller.ex.FileSizeException;
import cn.tedu.store.controller.ex.FileTypeException;
import cn.tedu.store.controller.ex.FileUploadEmptyException;
import cn.tedu.store.controller.ex.FileUploadIOException;
import cn.tedu.store.controller.ex.FileUploadStateException;
import cn.tedu.store.entity.User;
import cn.tedu.store.service.IUserService;
import cn.tedu.store.util.JsonResult;

@RestController
@RequestMapping("users")
public class UserController extends BaseController {

	@Autowired
	private IUserService service;

	/**
	 * 注册
	 * @param user 用户信息
	 * @return 返回用户信息
	 */
	@RequestMapping("reg")
	public JsonResult<Void> reg(User user) {

		service.reg(user);

		return new JsonResult<Void>(SUCCESS);

	}
	
	/**
	 * 登录操作
	 * @param username 用户名
	 * @param password 密码
	 * @param session session id信息
	 * @return 返回用户信息
	 */
	@RequestMapping("login")
	public JsonResult<User> login(String username, String password, HttpSession session) {
		User data = service.login(username, password);
		session.setAttribute("uid", data.getUid());
		session.setAttribute("username", data.getUsername());

		return new JsonResult<User>(SUCCESS, data);

	}
	/**
	 * 修改密码
	 * @param oldPassword 旧密码
	 * @param newPassword 新密码
	 * @param session session id 用户名
	 * @return 更新修改密码
	 */
	@RequestMapping("change_password")
	public JsonResult<Void> changePassword(@RequestParam("old_password") String oldPassword,
			@RequestParam("new_password") String newPassword, HttpSession session) {
		Integer uid = getUidFromSession(session);
		String username = getUsernameFromSession(session);
		service.changePassword(uid, username, oldPassword, newPassword);
		return new JsonResult<Void>(SUCCESS);

	}
	
	/**
	 * 上传用户数据
	 */
	@GetMapping("get_by_uid")
	public JsonResult<User> getByUid(HttpSession session){
		Integer uid = getUidFromSession(session);
		User data = service.getByUid(uid);
		return new JsonResult<User>(SUCCESS,data);
	}
	
	/**
	 * 
	 * @param session
	 * @param user
	 * @return
	 */
	@RequestMapping("change_info")
	public JsonResult<Void> changeInfo(HttpSession session,User user){
		Integer uid = getUidFromSession(session);
		String username = getUsernameFromSession(session);
		service.changeInfo(uid, username, user);
		return new JsonResult<Void>(SUCCESS);
	}
	
	private static final long FILE_MAX_SIZE = 700 * 1024;
	
	static final List<String> FILE_TYPE = new ArrayList<String>();
	
	static {
		FILE_TYPE.add("image/jpeg");
		FILE_TYPE.add("image/png");
	}
	
	
	@RequestMapping("change_avatar")
	public JsonResult<String> changeAvatar(@RequestParam("file")MultipartFile file,HttpSession session){
		
		
		//检查：上传的文件是否为空
		if(file.isEmpty()) {
			//是  为空  
			throw new FileUploadEmptyException("没有选择文件！或者上传的文件是0字节的");
			
		}
		//检查：上传的文件大小
		
		long size = file.getSize();
			if(size > FILE_MAX_SIZE) {
				throw new FileSizeException("上传文件过大！不允许上传超过"+FILE_MAX_SIZE/1024+"KB");
			}
		
		//检查：上传的文件类型
			
			if(!FILE_TYPE.contains(file.getContentType())) {
				throw new FileTypeException("文件上传失败！文件类型不匹配，只允许上传文件类型："+FILE_TYPE);
			}
				
		//上传文件夹
		String dirPath = session.getServletContext().getRealPath("upload");
		System.out.println("获取上传文件夹的路径："+dirPath);
		//创建 文件
		File dir = new File(dirPath);
		//判断文件是否存在
		if(!dir.exists()) {
			//否  则创建
			dir.mkdir();
		}
		
		//获取原始文件名
		String oldFilename = file.getOriginalFilename();
		System.out.println("获取原始文件名："+oldFilename);
		String suffix = "";
		
		int index = oldFilename.lastIndexOf(".");
		System.err.println("查找原始文件的点下标的最后一个位置 ："+index);
		
		if(index > 0) {
			suffix = oldFilename.substring(index);
			System.err.println("suffix : "+suffix);
		}
		
		//文件全名
		String filename = UUID.randomUUID().toString() + suffix;
		
		File dest = new File(dir,filename);
		
		try {
			
			file.transferTo(dest);
			
		} catch (IllegalStateException e) {
			e.printStackTrace();
			throw new FileUploadStateException("文件可能已经被移动或删除，不可访问到该文件");
		} catch (IOException e) {
			e.printStackTrace();
			throw new FileUploadIOException("出现读写错误！");
		}
		
		//获取头像路径
		String avatar = "/upload/"+filename;
		//通过session 获取用户id 和username
		Integer uid = getUidFromSession(session);
		
		String username = getUsernameFromSession(session);
		//执行 更新用户头像信息
		service.changeAvatar(uid, username, avatar);
		
		return new JsonResult<String>(SUCCESS,avatar);
		
	}
	
	
	
}
